package com.lengxf.pay.common.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.util.Map;

public class GlobalObjectMapper {

    protected static final Log log = LogFactory.get();
    private static final ObjectMapper INSTANCE;


    private final static TypeReference<Map<String, Object>> map_type = new TypeReference<>() {
    };

    static {
        INSTANCE = new ObjectMapper()
                .registerModule(new JavaTimeModule())
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    public static ObjectMapper getInstance() {
        return INSTANCE;
    }

    public static Map<String, Object> beanToMap(Object o) {
        return getInstance().convertValue(o, map_type);
    }

    public static String beanToJson(Object o) {
        if (o instanceof CharSequence) {
            return StrUtil.str((CharSequence) o);
        }
        try {
            return getInstance().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("toJson异常：", e);
            throw new RuntimeException(e);
        }
    }
}
